package com.cms.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cms.entity.Admin;
import com.cms.mapper.AdminMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author songfayuan
 * @since 2021-11-12
 */
@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    /**
     * 判断用户名是否存在
     *
     * @param username
     *            用户名(忽略大小写)
     * @return 用户名是否存在
     */
    public boolean usernameExists(String username) {
        if (StringUtils.isBlank(username)) {
            return false;
        }
        QueryWrapper<Admin> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        Long count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * 根据用户名查找管理员
     *
     * @param username
     *            用户名(忽略大小写)
     * @return 管理员，若不存在则返回null
     */
    public Admin findByUsername(String username) {
        if (StringUtils.isBlank(username)) {
            return null;
        }
        QueryWrapper<Admin> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 查找管理员分页
     *
     * @param pageNumber
     *            页码
     * @param pageSize
     *            每页记录数
     * @return 管理员分页
     */
    public Page<Admin> findPage(String name, String username, Integer pageNumber, Integer pageSize){
        QueryWrapper<Admin> queryWrapper = new QueryWrapper();
        if(StringUtils.isNotBlank(name)){
            queryWrapper.like("name",name);
        }
        if(StringUtils.isNotBlank(username)){
            queryWrapper.like("username",username);
        }
        queryWrapper.orderByDesc("createDate");
        return baseMapper.selectPage(new Page<>(pageNumber, pageSize),queryWrapper);
    }
}
